package com.shop.car.service.impl;

import com.shop.car.domain.ShopCar;
import com.shop.car.domain.ShopCarDetails;
import com.shop.car.feign.ProductRemote;
import com.shop.car.mapper.ShopCarMapper;
import com.shop.car.service.ShopCarService;
import com.shop.common.core.domain.Result;
import com.shop.common.redis.service.RedisService;
import com.shop.common.security.utils.SecurityUtils;
import com.shop.product.domain.PmsSkuInfo;
import com.shop.product.domain.PmsSkuSaleAttrValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.shop.car.constant.RedisConstant.COMPANY_NAME;

/**
 * @Author：作者姓名
 * @Package：com.shop.car.service.impl
 * @Project：Shop
 * @name：IShopCarServiceImpl
 * @Date：2024/6/21 18:28
 */
@Service
public class ShopCarServiceImpl implements ShopCarService {
    @Autowired
    private ShopCarMapper shopCarMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ProductRemote shopRemote;

    @Override
    public List<ShopCarDetails> findShopCar() {
        Long userId = SecurityUtils.getUserId();
        ArrayList<ShopCarDetails> shopCarDetails = new ArrayList<>();
        // 判断缓存中是否存在购物车信息
        if (redisService.hasKey(COMPANY_NAME + userId)) {
            Map<String, ShopCarDetails> cacheMap = redisService.getCacheMap(COMPANY_NAME + userId);
            return new ArrayList<>(cacheMap.values());
        }
        // 如果缓存中不存在，从数据库中查询
        ShopCar shopCarByUserId = shopCarMapper.findShopCarByUserId(userId);
        if (shopCarByUserId != null) {
            List<ShopCarDetails> shopCarDetailsByShopId = shopCarMapper.findShopCarDetailByShopId(shopCarByUserId.getCarId());
            return shopCarDetailsByShopId;
        }
        // 如果数据库中也不存在，则返回null
        return null;

    }

    @Override
    public void insertShopCar(Long skuId, Long detailsCount) {
        Long userId = SecurityUtils.getUserId();
        if (redisService.hasKey(COMPANY_NAME+userId)){
            handleExistingCartData(userId,skuId,detailsCount);
        } else {
            handleNonExistingCartData(userId,skuId,detailsCount);
        }
    }


    //完成购物车的修改
    @Override
    public void updateShopCar(Long skuId, Long detailsCount) {
        Long userId = SecurityUtils.getUserId();
        ShopCar shopCar=shopCarMapper.ShopCarList(userId);
        ShopCarDetails shopCarDetails = shopCarMapper.FindShopCarDetailsBySkuIdAndShopCarId(shopCar.getCarId(), skuId);
        if (detailsCount==0){
            shopCarMapper.ShopcarDetailsDelete(shopCarDetails.getDetailsId());
        }else {
            shopCarMapper.ShopCarDeatilsUpdate(shopCarDetails.getDetailsId(),detailsCount);
        }
    }

    //完成购物车的删除
    @Override
    public void deleteShopCar(Long carId) {
        shopCarMapper.ShopCarDelete(carId);
    }

    @Override
    public ShopCarDetails FindDetailsBySkuIdAndDetailsId(Long detailsId) {
        return shopCarMapper.FindDetailsBySkuIdAndDetailsId(detailsId);
    }

    @Override
    public List<ShopCarDetails> findByDetailsId(Long[] ids) {
        ArrayList<ShopCarDetails> list = new ArrayList<>();
        for (Long id : ids) {
            ShopCarDetails shopCarDetails=shopCarMapper.findByDetailsId(id);
            list.add(shopCarDetails);
        }
        return list;
    }

    //完成对总价的计算
    private void setTotalMoney(ShopCarDetails shopCarDetails) {
        BigDecimal skuPrice = shopCarDetails.getSkuPrice();
        int i = skuPrice.intValue();
        int totlaMOney = (int) (i * shopCarDetails.getDetailsCount());
        BigDecimal decimal = new BigDecimal(totlaMOney);
        shopCarDetails.setDetailsTotalMoney(decimal);
    }
    //完成对添加购物车时redis中存在数据的操作
    private void handleExistingCartData(Long userId, Long skuId, Long detailsCount) {
        ShopCarDetails cacheMapValue = redisService.getCacheMapValue(COMPANY_NAME + userId, skuId.toString());
        if(cacheMapValue!=null){
            //redis中存在商品详情
            cacheMapValue.setDetailsCount(cacheMapValue.getDetailsCount()+detailsCount);
            setTotalMoney(cacheMapValue);
            redisService.setCacheMapValue(COMPANY_NAME+userId,skuId.toString(),cacheMapValue);
            return;
        }
        // Redis 中不存在该商品详情，从数据库中获取
        ShopCar shopCarByUserId = shopCarMapper.findShopCarByUserId(userId);
        ShopCarDetails skuInfo = findSkuInfo(skuId, shopCarByUserId.getCarId(), detailsCount);

        // 将商品详情存入 Redis
        redisService.setCacheMapValue(COMPANY_NAME + userId, skuId.toString(), skuInfo);
    }

    //完成添加购物车对redis中无数据时的操作
    private void handleNonExistingCartData(Long userId, Long skuId, Long detailsCount) {
        // 查询数据库中是否存在购物车数据
        ShopCar shopCarByUserId = shopCarMapper.FindShopCarList(userId);
        if (shopCarByUserId == null) {
            // 数据库中不存在购物车数据，创建新的购物车
            createNewCart(userId, skuId, detailsCount);
            return;
        }

        // 数据库中存在购物车数据，直接操作购物车明细表
        handleExistingCartInDatabase(userId, skuId, detailsCount, shopCarByUserId);
    }


    //数据库中不存在购物侧信息
    private void createNewCart(Long userId, Long skuId, Long detailsCount) {
        ShopCar shopCar = new ShopCar();
        shopCar.setCarId(userId);
        shopCar.setUserId(userId);

        // 添加购物车到数据库
        Integer i = shopCarMapper.ShopCarAdd(shopCar);

        // 查询商品数据并添加到购物车明细表
        ShopCarDetails skuInfo = findSkuInfo(skuId, shopCar.getCarId(), detailsCount);
        shopCarMapper.insertShopCarDetail(skuInfo);

        // 将商品详情存入 Redis
        redisService.setCacheMapValue(COMPANY_NAME + userId, skuId.toString(), skuInfo);
    }

    //数据库中存在购物车信息
    private void handleExistingCartInDatabase(Long userId, Long skuId, Long detailsCount, ShopCar shopCarByUserId) {
        // 查询购物车明细中是否存在该商品
        ShopCarDetails shopCarDetails = shopCarMapper.FindShopCarDetailsBySkuIdAndShopCarId(shopCarByUserId.getCarId(), skuId);
        if (shopCarDetails == null) {
            // 购物车明细中不存在该商品，查询商品数据并添加到购物车明细表
            ShopCarDetails skuInfo = findSkuInfo(skuId, shopCarByUserId.getCarId(), (long) detailsCount);
            shopCarMapper.ShopCarDetailsAdd(skuInfo);
        } else {
            // 购物车明细中已存在该商品，更新商品数量
            shopCarDetails.setDetailsCount(shopCarDetails.getDetailsCount() + detailsCount);
            shopCarMapper.ShopCarDeatilsUpdate(shopCarDetails.getDetailsId(), shopCarDetails.getDetailsCount());
        }
    }

    // 添加新的商品明细
    private ShopCarDetails findSkuInfo(Long skuId, Long carId, Long detailsCount) {
        ShopCarDetails shopCarDetails = new ShopCarDetails();

//        根据skuID 得到商品信息
        Result<PmsSkuInfo> info = shopRemote.getSkuInfo(skuId);
        PmsSkuInfo pmsSkuInfo = info.getData();
        //根据skuId 获得销售属性
        Result<List<PmsSkuSaleAttrValue>> saleAttrInfo = shopRemote.getSkuSaleAttr(skuId);
        List<PmsSkuSaleAttrValue> pmsSkuSaleAttr = saleAttrInfo.getData();
        StringBuilder stringBuilder = new StringBuilder();
        pmsSkuSaleAttr.forEach(item -> {
            stringBuilder.append(item.getAttrValue());
        });

        //封装购物车明细对象
        shopCarDetails.setSkuId(skuId);
        shopCarDetails.setCarId(carId);
        shopCarDetails.setDetailsCount(detailsCount);
        shopCarDetails.setBrandLogo(pmsSkuInfo.getSkuDefaultImg());
        shopCarDetails.setSaleAttrs(stringBuilder.toString());
        shopCarDetails.setSkuPrice(pmsSkuInfo.getPrice());
        shopCarDetails.setSkuTitle(pmsSkuInfo.getSkuTitle());
        setTotalMoney(shopCarDetails);
        return shopCarDetails;
    }


}
